package be.destin.memolog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionMemoManager {

	final public static String defaultBasket = "mark_basket";
	final public static String basketAttribute = "currentbasket";

	HttpServletRequest request;
	
	public SessionMemoManager(HttpServletRequest req) {
		if (req != null) {
			this.request = req;
			String basketName = req.getParameter(basketAttribute);
			if (basketName != null && !basketName.isEmpty()) {
				this.setBasketName(basketName);
			}
		}
	}

	/**
	 * @return the request
	 */
	public HttpServletRequest getRequest() {
		return request;
	}

	/**
	 * @param request the request to set
	 */
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public String getBasketName() {
		if (this.request == null) return defaultBasket;
		HttpSession session = this.request.getSession();
		if (session == null) return defaultBasket;
		String basketName = (String) session.getAttribute(basketAttribute);
		if (basketName == null || basketName.isEmpty()) return defaultBasket;
		return basketName;
	}

	public void setBasketName(String basketName) {
		if (this.request == null) return;
		if (basketName == null || basketName.isEmpty()) {
			basketName = defaultBasket; // This function must NOT be called if no basketName has to be imposed!
		}
		HttpSession session = this.request.getSession();
		if (session == null) return;
		session.setAttribute(basketAttribute,basketName);
	}
}
